import 'package:flutter/material.dart';

typedef RefreshCallback = Future<void> Function();
typedef LoadMoreCallback = Future<void> Function();

class MyListView extends StatefulWidget {
  MyListView(
      {Key? key,
      required this.itemCount,
      required this.itemBuilder,
      this.onRefresh,
      required this.hasMore,
      this.reverse = false,
      this.controller,
      this.itemExtent,
      this.loadMore})
      : super(key: key);

  final int itemCount;
  final IndexedWidgetBuilder itemBuilder;
  final RefreshCallback? onRefresh;
  bool hasMore = true;
  final bool reverse;
  final LoadMoreCallback? loadMore;
  final double? itemExtent;
  final ScrollController? controller;
  @override
  _MyListViewState createState() => _MyListViewState();
}

class _MyListViewState extends State<MyListView> {
  final ScrollController _controller = ScrollController();

  Widget createListWidget() {
    Widget listWidget = Scrollbar(
        controller: widget.controller ?? _controller,
        child: ListView.builder(
          reverse: widget.reverse,
          controller: widget.controller ?? _controller,
          itemExtent: widget.itemExtent, // 每个块的大小，使拖动滚动条更平滑
          itemCount: widget.itemCount + 1,
          itemBuilder: (context, index) {
            if (index == widget.itemCount) {
              if (widget.hasMore && widget.loadMore != null) {
                widget.loadMore!();
                return const Text("正在加载");
              } else if (widget.itemCount == 0) {
                return const Text("no data");
              } else {
                return Text("没有了,共计${widget.itemCount}条数据");
              }
            }
            return widget.itemBuilder(context, index);
          },
        ));
    if (widget.reverse || widget.onRefresh == null) {
      return listWidget;
    } else {
      return RefreshIndicator(onRefresh: widget.onRefresh!, child: listWidget);
    }
  }

  @override
  Widget build(BuildContext context) {
    return createListWidget();
  }
}
